/**
 * 统一防抖工具
 * 提供标准化的防抖延迟配置
 */

// 标准防抖延迟配置
export const DEBOUNCE_DELAYS = {
  // 快速响应 - 用于UI状态更新
  FAST: 50,
  // 标准延迟 - 用于搜索输入
  NORMAL: 300,
  // 慢速延迟 - 用于复杂计算
  SLOW: 500,
  // 网络请求 - 避免频繁API调用
  NETWORK: 1000
};

/**
 * 创建防抖函数
 * @param {Function} fn 要防抖的函数
 * @param {number} delay 延迟时间（毫秒）
 * @param {Object} options 选项
 * @param {boolean} options.immediate 是否立即执行第一次
 * @returns {Function} 防抖后的函数
 */
export function debounce(fn, delay = DEBOUNCE_DELAYS.NORMAL, options = {}) {
  const { immediate = false } = options;
  let timeoutId = null;
  let hasBeenCalled = false;

  return function debounced(...args) {
    const context = this;

    // 立即执行逻辑
    if (immediate && !hasBeenCalled) {
      fn.apply(context, args);
      hasBeenCalled = true;
    }

    // 清除之前的定时器
    if (timeoutId) {
      clearTimeout(timeoutId);
    }

    // 设置新的定时器
    timeoutId = setTimeout(() => {
      if (!immediate) {
        fn.apply(context, args);
      }
      hasBeenCalled = false;
      timeoutId = null;
    }, delay);
  };
}

/**
 * 创建可取消的防抖函数
 * @param {Function} fn 要防抖的函数
 * @param {number} delay 延迟时间
 * @returns {Object} 包含防抖函数和取消函数
 */
export function createCancelableDebounce(fn, delay = DEBOUNCE_DELAYS.NORMAL) {
  let timeoutId = null;

  const debouncedFn = function(...args) {
    const context = this;
    
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    
    timeoutId = setTimeout(() => {
      fn.apply(context, args);
      timeoutId = null;
    }, delay);
  };

  const cancel = () => {
    if (timeoutId) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
  };

  const flush = function(...args) {
    cancel();
    return fn.apply(this, args);
  };

  return {
    fn: debouncedFn,
    cancel,
    flush
  };
}

/**
 * 节流函数
 * @param {Function} fn 要节流的函数
 * @param {number} delay 节流间隔
 * @returns {Function} 节流后的函数
 */
export function throttle(fn, delay = DEBOUNCE_DELAYS.NORMAL) {
  let timeoutId = null;
  let lastExecTime = 0;

  return function throttled(...args) {
    const context = this;
    const currentTime = Date.now();

    if (currentTime - lastExecTime > delay) {
      fn.apply(context, args);
      lastExecTime = currentTime;
    } else {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      
      timeoutId = setTimeout(() => {
        fn.apply(context, args);
        lastExecTime = Date.now();
        timeoutId = null;
      }, delay - (currentTime - lastExecTime));
    }
  };
}

// 预定义的常用防抖函数
export const debounceFast = (fn) => debounce(fn, DEBOUNCE_DELAYS.FAST);
export const debounceNormal = (fn) => debounce(fn, DEBOUNCE_DELAYS.NORMAL);
export const debounceSlow = (fn) => debounce(fn, DEBOUNCE_DELAYS.SLOW);
export const debounceNetwork = (fn) => debounce(fn, DEBOUNCE_DELAYS.NETWORK); 